// 操作共享变量会有问题的售票系统代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

#include "Mutex.hpp"

using namespace quitesix;

int ticket = 1000;
// pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
// pthread_mutex_t lock;

void *route(void *arg)
{
    Mutex *lock = static_cast<Mutex *>(arg);
    while (1)
    {
        // RAII。guard在构造时申请锁，在析构时释放锁
        MutexGuard guard(lock);
        if (ticket > 0)
        {
            usleep(1000);
            printf("sells ticket:%d\n", ticket);
            ticket--;
        }
        else
        {
            break;
        }
    }

    return nullptr;
}

// char *id = (char *)arg;
// while (1)
// {
//     // pthread_mutex_lock(&lock);
//     if (ticket > 0) // 1. 判断
//     {
//         usleep(1000);                               // 模拟抢票花的时间
//         printf("%s sells ticket:%d\n", id, ticket); // 2. 抢到了票
//         ticket--;                                   // 3. 票数--
//         // pthread_mutex_unlock(&lock);
//     }
//     else
//     {
//         // pthread_mutex_unlock(&lock);
//         break;
//     }
// }

int main(void)
{
    // pthread_mutex_init(&lock, nullptr);

    Mutex lock;

    pthread_t t1, t2, t3, t4;

    // pthread_create(&t1, NULL, route, (void *)"thread 1");
    // pthread_create(&t2, NULL, route, (void *)"thread 2");
    // pthread_create(&t3, NULL, route, (void *)"thread 3");
    // pthread_create(&t4, NULL, route, (void *)"thread 4");

    pthread_create(&t1, NULL, route, (void *)&lock);
    pthread_create(&t2, NULL, route, (void *)&lock);
    pthread_create(&t3, NULL, route, (void *)&lock);
    pthread_create(&t4, NULL, route, (void *)&lock);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_join(t4, NULL);

    // pthread_mutex_destroy(&lock);
}